package com.lark.web.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.jcraft.jsch.Session;
import com.lark.common.core.page.PageDomain;
import com.lark.common.exception.CustomException;
import com.lark.common.utils.sql.SqlUtil;
import com.lark.web.domain.Host;
import com.lark.web.service.HostService;
import com.lark.web.ssh.service.SSHUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.pagehelper.PageInfo;
import com.lark.common.core.domain.BaseEntity;
import com.lark.common.core.service.BaseServiceImpl;
import com.lark.web.mapper.FileSystemMapper;
import com.lark.web.domain.FileSystem;
import com.lark.web.service.FileSystemService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文件中心Service业务层处理
 *
 * @author fei
 * @email zhangfei0210@163.com
 * @date 2024-09-10
 */
@Service
public class FileSystemServiceImpl extends BaseServiceImpl<FileSystemMapper, FileSystem> implements FileSystemService {

    private static final Logger log = LoggerFactory.getLogger(FileSystemServiceImpl.class);

    @Autowired
    private HostService hostService;

    /**
     * 分页查询文件中心列表
     *
     * @param fileSystem 文件中心
     * @return 文件中心
     */
    @Override
    public PageInfo<FileSystem> findPage(FileSystem fileSystem) {
        PageDomain page = fileSystem.getPage();
        Integer pageNum = page.getPageNum();
        Integer pageSize = page.getPageSize();
        if (com.lark.common.utils.StringUtils.isNotNull(pageNum) && com.lark.common.utils.StringUtils.isNotNull(pageSize)) {
            Boolean reasonable = page.getReasonable();
            PageHelper.startPage(pageNum, pageSize, null).setReasonable(reasonable);
        }
        List<FileSystem> fileSystemList = listFiles(fileSystem.getIp(), fileSystem.getPath());
        fileSystemList = fileSystemList.stream().sorted(Comparator.comparing(FileSystem::getFileName)).collect(Collectors.toList());
        if (StringUtils.isNotBlank(page.getOrderByColumn()) && Objects.equals(page.getIsAsc(), "asc")) {
            fileSystemList = fileSystemList.stream().sorted(Comparator.comparing(FileSystem::getFileUpdateTime)).collect(Collectors.toList());
        } else if (StringUtils.isNotBlank(page.getOrderByColumn()) && Objects.equals(page.getIsAsc(), "desc")) {
            fileSystemList = fileSystemList.stream().sorted(Comparator.comparing(FileSystem::getFileUpdateTime).reversed()).collect(Collectors.toList());
        }

        return new PageInfo(fileSystemList);
    }

    /**
     * 列出文件列表
     *
     * @param ip
     * @param path
     * @return
     */
    public List<FileSystem> listFiles(String ip, String path) {
        if (StringUtils.isBlank(ip)) {
            throw new CustomException("请选择IP！");
        }
        if (StringUtils.isBlank(path)) {
            path = "/";
        }
        String command = "ls -lh --full-time " + path;
        Host remoteHost = hostService.getEnalbeList(ip).get(0);
        Session session = SSHUtil.openSession(remoteHost.getHostIp(), 22, remoteHost.getAccount(),
                remoteHost.getPassword());
        String execResponse = SSHUtil.exec(session, command);
        List<FileSystem> lists = new ArrayList<>();
        String[] lineArray = execResponse.split("\n");
        for (int i = 1; i < lineArray.length; i++) {
            List<String> oneline = SSHUtil.ignoreNull(lineArray[i]);
            FileSystem ffile = new FileSystem();
            ffile.setFileName(oneline.get(8));
            ffile.setFileSize(oneline.get(4));
            ffile.setFileType(SSHUtil.getTypeOfFile(oneline.get(0)));
            ffile.setFileUpdateTime(SSHUtil.subDateString(oneline.get(5) + " " + oneline.get(6)));
            lists.add(ffile);
        }
        return lists;
    }

    /**
     * 查看文件内容
     *
     * @param fileName
     */
    @Override
    public String viewFile(String ip, String fileName) {
        if (StringUtils.isBlank(fileName)) {
            throw new RuntimeException("fileName不能为空！");
        }
        if (Objects.equals(fileName, "/")) {
            throw new RuntimeException("fileName不能为根目录！");
        }
        String command = "cat " + fileName;
        Host remoteHost = hostService.getEnalbeList(ip).get(0);
        Session session = SSHUtil.openSession(remoteHost.getHostIp(), 22, remoteHost.getAccount(),
                remoteHost.getPassword());
        String execResponse = SSHUtil.exec(session, command);
        return execResponse;
    }

    /**
     * 删除文件或者文件夹
     *
     * @param fileName
     */
    @Override
    public String removeFile(String ip, String fileName) {
        if (StringUtils.isBlank(fileName)) {
            throw new RuntimeException("fileName不能为空！");
        }
        if (Objects.equals(fileName, "/")) {
            throw new RuntimeException("fileName不能为根目录！");
        }
        String command = "rm -rf " + fileName;
        Host remoteHost = hostService.getEnalbeList(ip).get(0);
        Session session = SSHUtil.openSession(remoteHost.getHostIp(), 22, remoteHost.getAccount(),
                remoteHost.getPassword());
        String execResponse = SSHUtil.exec(session, command);
        return execResponse;
    }

    /**
     * 创建文件或者文件夹
     *
     * @param fileName
     */
    @Override
    public String createFile(String ip, String fileType, String fileName, String filePath) {
        if (StringUtils.isBlank(fileName)) {
            throw new RuntimeException("fileName不能为空！");
        }
        String command = "ls";
        if (Objects.equals(fileType, "directory")) {
            command = "mkdir -p " + filePath + fileName;

        } else if (Objects.equals(fileType, "regular_file")) {
            command = "touch " + filePath + fileName;
        }
        Host remoteHost = hostService.getEnalbeList(ip).get(0);
        Session session = SSHUtil.openSession(remoteHost.getHostIp(), 22, remoteHost.getAccount(),
                remoteHost.getPassword());
        String execResponse = SSHUtil.exec(session, command);
        return execResponse;
    }

    @Override
    public void renameFile(String ip, String fileName, String filePath, String newFileName) {
        String command = "mv " + filePath + fileName + " " + filePath + newFileName;
        Host remoteHost = hostService.getEnalbeList(ip).get(0);
        Session session = SSHUtil.openSession(remoteHost.getHostIp(), 22, remoteHost.getAccount(),
                remoteHost.getPassword());
        String execResponse = SSHUtil.exec(session, command);
    }

    /**
     * 获取单条数据
     *
     * @param fileSystem 文件中心
     * @return 文件中心
     */
    @Override
    public FileSystem get(FileSystem fileSystem) {
        FileSystem dto = super.get(fileSystem);
        return dto;
    }

    /**
     * 获取单条数据
     *
     * @param id 文件中心id
     * @return 文件中心
     */
    @Override
    public FileSystem get(String id) {
        FileSystem dto = super.get(id);
        return dto;
    }

    /**
     * 查询文件中心列表
     *
     * @param fileSystem 文件中心
     * @return 文件中心
     */
    @Override
    public List<FileSystem> findList(FileSystem fileSystem) {
        List<FileSystem> fileSystemList = super.findList(fileSystem);
        return fileSystemList;
    }

    /**
     * 保存文件中心
     *
     * @param fileSystem
     * @return 结果
     */
    @Override
    public boolean save(FileSystem fileSystem) {
        return super.save(fileSystem);
    }

    /**
     * 删除文件中心信息
     *
     * @param fileSystem
     * @return 结果
     */
    @Override
    public boolean remove(FileSystem fileSystem) {
        return super.remove(fileSystem);
    }

    /**
     * 批量删除文件中心
     *
     * @param ids 需要删除的文件中心ID
     * @return 结果
     */
    @Transactional(readOnly = false)
    @Override
    public int deleteFileSystemByIds(String[] ids) {
        return mapper.deleteFileSystemByIds(ids, BaseEntity.DEL_FLAG_DELETE);
    }

}
